package com.itjob.scott.student.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.google.gson.Gson;
import com.itjob.scott.student.entity.StudentEntity;
import com.itjob.scott.student.service.StudentService;


public class LoginServlet extends HttpServlet {
	
	private static final long serialVersionUID = -8502683218223004966L;
	
	private WebApplicationContext ctx = null;
	
	private StudentService service = null;
	

	@Override
	public void init(ServletConfig config) throws ServletException {
		ServletContext application = config.getServletContext();
		ctx = WebApplicationContextUtils.getWebApplicationContext(application);
		service = ctx.getBean(StudentService.class);
		
	}
	
	
	//登录
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");

		StudentEntity entity = new StudentEntity();
		entity.setUsername(username);
		entity.setPassword(password);
		
		response.setCharacterEncoding("UTF-8");
		Gson gson = new Gson();
		PrintWriter out = response.getWriter();
		Map<String, Object> returnMap = new HashMap<String, Object>();
		if(service.loginValidate(entity)) {
			// return welcome
			request.getSession().setAttribute("studentEntity", entity);
			
			returnMap.put("status", "1");  //1代表成功,0代表失败
			returnMap.put("url", "welcome.jsp");  //1代表成功,0代表失败
		} else {
			// return  page
			returnMap.put("status", "0");  //1代表成功,0代表失败
			returnMap.put("errorInfo", "用户名或密码不正确!");  //1代表成功,0代表失败
		}
		
		String returnValue = gson.toJson(returnMap);
		out.write(returnValue);
		out.flush();
		out.close();
		
	}
	


}
